const db = require("@/db/index");

// 分页查询工资记录
exports.querySalary = (req, resp) => {
  try {
    const {
      pageSize = 10,
      pageNum = 1,
      staffName,
      position,
      sendTimeStart,
      sendTimeEnd,
    } = req.body;

    // 构建查询条件
    let conditions = [];
    let params = [];

    if (staffName) {
      conditions.push("staff_name LIKE ?");
      params.push(`%${staffName}%`);
    }
    if (position) {
      conditions.push("position LIKE ?");
      params.push(`%${position}%`);
    }
    if (sendTimeStart && sendTimeEnd) {
      // 确保时间格式正确
      conditions.push("send_time BETWEEN ? AND ?");
      params.push(sendTimeStart, sendTimeEnd);
    } else if (sendTimeStart) {
      // 只输入开始时间
      conditions.push("send_time >= ?");
      params.push(sendTimeStart);
    } else if (sendTimeEnd) {
      // 只输入结束时间
      conditions.push("send_time <= ?");
      params.push(sendTimeEnd);
    }

    // 组装WHERE子句
    const whereClause =
      conditions.length > 0 ? "WHERE " + conditions.join(" AND ") : "";

    // 查询总数
    const countSql = `SELECT COUNT(*) as total FROM employeesalary ${whereClause}`;
    db.query(countSql, params, (err, totalResult) => {
      if (err) return resp.err(err);
      const total = totalResult[0].total;

      // 查询数据
      const offset = (pageNum - 1) * pageSize;
      const dataSql = `
        SELECT *
        FROM employeesalary
        ${whereClause}
        ORDER BY send_time DESC, id DESC
        LIMIT ? OFFSET ?
      `;

      db.query(dataSql, [...params, pageSize, offset], (err, rows) => {
        if (err) return resp.err(err);
        resp.ok({
          total,
          list: rows,
          pageSize,
          pageNum,
        });
      });
    });
  } catch (error) {
    resp.err(error);
  }
};

// 新增工资记录
exports.addSalary = (req, resp) => {
  try {
    const salaryInfo = req.body;

    // 必填字段校验
    if (!salaryInfo.send_time) return resp.err("发放时间不能为空");
    if (!salaryInfo.staff_no) return resp.err("员工工号不能为空");
    if (!salaryInfo.staff_name) return resp.err("员工姓名不能为空");

    // 构建插入数据（所有数值字段默认设为0）
    const insertData = {
      send_time: salaryInfo.send_time,
      staff_no: salaryInfo.staff_no,
      staff_name: salaryInfo.staff_name,
      position: salaryInfo.position || null,
      department_name: salaryInfo.department_name || null,
      base_pay: salaryInfo.base_pay || 0,
      living_allowance: salaryInfo.living_allowance || 0,
      full_attendance: salaryInfo.full_attendance || 0,
      overtime_pay: salaryInfo.overtime_pay || 0,
      insurance: salaryInfo.insurance || 0,
      absenteeism_fee: salaryInfo.absenteeism_fee || 0,
      other_deductions: salaryInfo.other_deductions || 0,
      net_salary: salaryInfo.net_salary || 0,
      achievements: salaryInfo.achievements || 0,
      remarks: salaryInfo.remarks || null,
    };

    // 执行插入
    const insertSql = "INSERT INTO employeesalary SET ?";
    db.query(insertSql, insertData, (err, result) => {
      if (err) {
        console.error("新增工资记录失败:", err);
        return resp.err("新增失败: " + err.message);
      }
      if (result.affectedRows !== 1) return resp.err("新增失败");

      resp.ok(
        {
          id: result.insertId,
          ...insertData,
          create_time: new Date(), // 数据库会自动填充
        },
        "新增成功"
      );
    });
  } catch (error) {
    console.error("新增异常:", error);
    resp.err("新增失败: " + error.message);
  }
};

// 删除工资记录
exports.deleteSalary = (req, resp) => {
  try {
    const ids = req.body;

    // 校验ID列表
    if (!ids || !Array.isArray(ids) || ids.length === 0) {
      return resp.err("请选择要删除的记录");
    }

    // 执行删除
    const deleteSql = "DELETE FROM employeesalary WHERE id IN (?)";
    db.query(deleteSql, [ids], (err, result) => {
      if (err) {
        console.error("删除失败:", err);
        return resp.err("删除失败: " + err.message);
      }
      if (result.affectedRows === 0) return resp.err("未找到记录");

      resp.ok(
        { deletedCount: result.affectedRows },
        `成功删除${result.affectedRows}条记录`
      );
    });
  } catch (error) {
    console.error("删除异常:", error);
    resp.err("删除失败: " + error.message);
  }
};

// 修改工资记录
exports.updateSalary = (req, resp) => {
  try {
    const salaryInfo = req.body;

    // 校验ID
    if (!salaryInfo.id) return resp.err("记录ID不能为空");

    // 构建更新数据
    const updateData = {};
    const allowedFields = [
      "send_time",
      "staff_no",
      "staff_name",
      "position",
      "department_name",
      "base_pay",
      "achievements",
      "living_allowance",
      "full_attendance",
      "overtime_pay",
      "insurance",
      "absenteeism_fee",
      "other_deductions",
      "net_salary",
      "remarks",
    ];

    allowedFields.forEach((field) => {
      if (salaryInfo[field] !== undefined) {
        updateData[field] =
          salaryInfo[field] ||
          (typeof salaryInfo[field] === "number" ? 0 : null);
      }
    });

    // 无有效字段时返回错误
    if (Object.keys(updateData).length === 0) {
      return resp.err("未提供修改字段");
    }

    // 执行更新
    const updateSql = "UPDATE employeesalary SET ? WHERE id = ?";
    db.query(updateSql, [updateData, salaryInfo.id], (err, result) => {
      if (err) {
        console.error("更新失败:", err);
        return resp.err("更新失败: " + err.message);
      }
      if (result.affectedRows === 0) return resp.err("未找到记录");

      // 返回更新后的数据
      const selectSql = "SELECT * FROM employeesalary WHERE id = ?";
      db.query(selectSql, [salaryInfo.id], (err, rows) => {
        if (err) return resp.err("查询失败");
        resp.ok(rows[0], "更新成功");
      });
    });
  } catch (error) {
    console.error("更新异常:", error);
    resp.err("更新失败: " + error.message);
  }
};
